//
//  SISSFindHouseResourcesViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/31.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSFindHouseResourcesViewController.h"
#import "SISSHousingCell.h"
#import "SISSRecommendPassengerViewController.h"
#import "SISSMapViewController.h"
#import "SISSSearchViewController.h"
#import "SISSHouseResourceDetailVC.h"
#import "SISSJsonRequestNetworkingManager+Resources.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSComboBoxView.h"
#import "SISSTabBarController.h"
#import "SISSHouseNumVerifyViewController.h"
//#import "SISSHouseEnrollFirstViewController.h"



static NSString * const housingCellID = @"housingCellID";

@interface SISSFindHouseResourcesViewController ()<UITableViewDelegate,UITableViewDataSource,SISSHousingCellDelegate,SISSComboBoxViewDelegate>

/** 房源数组 */
@property (strong, nonatomic) NSMutableArray<SISSHouseResourceModel *> *houseResourceArr;

/** tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/** 筛选视图 */
@property (weak, nonatomic) SISSComboBoxView *filterView;

/* hintLabel */
@property (weak, nonatomic) UILabel *hintLabel;

/** 可见范围 */
@property (assign, nonatomic) NSInteger visibleRange;
/** 排序规则 */
@property (assign, nonatomic) NSInteger orderAttrs;
/** 区域 */
@property (copy, nonatomic) NSString *region;
/** 街道办 */
@property (copy, nonatomic) NSString *regionDetail;
/** 价格 */
@property (copy, nonatomic) NSString *price;
/** 户型 */
@property (copy, nonatomic) NSString *houseType;
/** 面积 */
@property (copy, nonatomic) NSArray *area;
/** 朝向 */
@property (copy, nonatomic) NSArray *direction;
/** 装修程度 */
@property (copy, nonatomic) NSArray *decoration;
/** pageNo */
@property (assign, nonatomic) NSInteger pageNo;


@end

@implementation SISSFindHouseResourcesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageNo = 1;
    
    // 添加右侧 地图、搜索按钮
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:@selector(searchItemClickAction)];
    UIBarButtonItem *locationItem =  [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"map"] style:UIBarButtonItemStylePlain target:self action:@selector(locationItemClickAction)];
    [searchItem setTintColor:COLOR(0x8998A5)];
    [locationItem setTintColor:COLOR(0x8998A5)];
    self.navigationItem.rightBarButtonItems = @[searchItem,locationItem];
    
    
    // 加载数据
    [self requestFilterSearchHouseResourceData];
    
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf upDownLoadData];
    }];
    
    [kSISSRefresh prepareFooterRefresh:self.tableView reloadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeReloadMore;
        [weakSelf reloadMoreData];
    }];
    self.tableView.mj_footer.hidden = YES;
}

/**
 房源登记
 */
//- (void)registerButtonAction {
//    
//    SISSHouseNumVerifyViewController *vc = [[SISSHouseNumVerifyViewController alloc] init];
////    SISSHouseEnrollFirstViewController *vc = [[SISSHouseEnrollFirstViewController alloc] init];
//    vc.title = @"房源登记";
//    vc.isRegistration = NO;
//    [self.navigationController pushViewController:vc animated:YES];
//}

/**
 地图找房点击事件
 */
- (void)locationItemClickAction {
    
    SISSMapViewController *mapVC = [[SISSMapViewController alloc] init];
    
    [self.navigationController pushViewController:mapVC animated:YES];
}


/**
 右侧搜索按钮点击事件
 */
- (void)searchItemClickAction {
    
    SISSSearchViewController *searchVC = [[SISSSearchViewController alloc] init];
    searchVC.modalPresentationStyle = UIModalPresentationFullScreen;
    searchVC.searchType = SISSSearchTypeHouse;
    [self presentViewController:searchVC animated:NO completion:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.filterView.comBoBoxView dismissPopView];
}



#pragma mark - 代理
#pragma mark -- SISSHousingCellDelegate 推荐客源
- (void)housingCellRecommendButtonDidClick:(UIButton *)button {
    
    SISSHousingCell *cell = (SISSHousingCell *)button.nextResponder.nextResponder;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    SISSHouseResourceModel *model = self.houseResourceArr[indexPath.row];
    
    SISSRecommendPassengerViewController *vc = [[SISSRecommendPassengerViewController alloc] init];
    vc.title = @"推荐客源";
    vc.isFind = YES;
    vc.ahrId = model.ID;
    vc.recommendSuccessBlock = ^{
        [self upDownLoadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- SISSComboBoxViewDelegate 筛选
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"售价"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"户型"]) {
        self.houseType = title;
    }
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestFilterSearchHouseResourceData];
        
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestFilterSearchHouseResourceData];
    
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {
    
    if ([title isEqualToString:@"可见范围"]) {
        self.visibleRange = 2;
    } else if ([title isEqualToString:@"面积"]) {
        self.area = @[];
        self.area = subtitles;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = @[];
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = @[];
        self.decoration = subtitles;
    }
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    self.pageNo = 1;
    [self requestFilterSearchHouseResourceData];
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.visibleRange = 1;
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}

#pragma mark -- UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    [tableView tableViewDisplayWithMessage:@"没有找到相关房源！" ifNecessaryForRowCount:self.houseResourceArr.count];
    if (self.houseResourceArr.count != 0) {
        return self.houseResourceArr.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    SISSHousingCell *cell = [tableView dequeueReusableCellWithIdentifier:housingCellID];
    cell.delegate = self;
    
    cell.houseResourceModel = self.houseResourceArr[indexPath.row];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 去除tableView的选中状态
    SISSHouseResourceDetailVC *vc = [[SISSHouseResourceDetailVC alloc] init];
    vc.title = @"房源详情";
    vc.isFind = YES;
    SISSHouseResourceModel *houseModel = self.houseResourceArr[indexPath.row];
    vc.houseResourceModel = houseModel;
    if (houseModel.read != 1) {
        
        [kNetworkManager setHouseResourceReadWithHouseId:houseModel.ID success:^(id responseObject) {
            
            if ([responseObject[@"code"] integerValue] == 200) {
                NSLog(@"插入成功！");
            }
            
        } failed:^(NSError *error) {
            
            NSLog(@"%@",error);
        }];
    }
    self.houseResourceArr[indexPath.row].read = 1;
    [self.tableView reloadData];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 点击排序按钮
- (void)sortedButtonDidClick:(UIButton *)button {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor blackColor];
    [alertController addTapDisMissAction];
    
    NSArray *sortArr = @[@"默认排序", @"售价从低到高", @"售价从高到低", @"均价从低到高", @"均价从高到低"];
    
    for (int i = 0; i < sortArr.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:sortArr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.orderAttrs = i;
            kSISSRefresh.refreshType = SISSRefressTypeUpDown;
            self.pageNo = 1;
            [self requestFilterSearchHouseResourceData];
        }];
        
        [alertController addAction:action];
    }

    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownLoadData {
    
    self.pageNo = 1;
    
    [self requestFilterSearchHouseResourceData];
    
}

- (void)reloadMoreData {
    
    self.pageNo += 1;
    
    [self requestFilterSearchHouseResourceData];
}


#pragma mark - 2.4.1 筛选房源、找房源的请求
- (void)requestFilterSearchHouseResourceData {
    
    // 非空处理
    NSString *keyword = self.keyword ? self.keyword : @"";
    NSInteger visibleRange = self.visibleRange == 2 ? self.visibleRange : 1;
    NSInteger orderAttrs = self.orderAttrs ? self.orderAttrs : 0;
    NSString *region = self.region ? self.region : @"不限";
    NSString *regionDetail = self.regionDetail ? self.regionDetail : @"不限";
    NSString *price = self.price ? self.price : @"";
    NSString *houseType = self.houseType ? self.houseType : @"不限";
    
    NSDictionary *parameters = @{@"keyword":keyword,
                                 @"visibleRange":@(visibleRange),
                                 @"orderAttrs":@(orderAttrs),
                                 @"region":region,
                                 @"regionDetail":regionDetail,
                                 @"price":price,
                                 @"houseType":houseType,
                                 @"area":self.area ,
                                 @"direction":self.direction,
                                 @"decoration":self.decoration
                                 };
    //加载搜索跳转找房源的数据
    WeakSelf
    [kJsonRequestNetworkingManager requestFilterSearchHouseResourceWithPageNo:self.pageNo parameters:parameters success:^(SISSBasePagingModel *baseModel) {
        
        NSArray *houseResources = [NSArray yy_modelArrayWithClass:[SISSHouseResourceModel class] json:baseModel.data];
        
        if (weakSelf.houseResourceArr.count != 0 && kSISSRefresh.refreshType == SISSRefressTypeUpDown) {
            
            [weakSelf.houseResourceArr removeAllObjects];
        }
        
        for (int i = 0; i < houseResources.count; i++) {
            
            [weakSelf.houseResourceArr addObject:houseResources[i]];
        }

//        weakSelf.hintLabel.hidden = NO;
        weakSelf.hintLabel.text = [NSString stringWithFormat:@"共找到%zd条符合条件的信息",weakSelf.houseResourceArr.count];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.hintLabel.hidden = YES;
        });
        
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [weakSelf.tableView reloadData];
            weakSelf.tableView.mj_footer.hidden = baseModel.total == 0;
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (weakSelf.houseResourceArr.count >= baseModel.total) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }];
        
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        NSLog(@"%@",error);
    }];
    
}



#pragma mark - 设置UI
- (void)setupSubviews {
    [super setupSubviews];
    
    // 添加筛选视图
    SISSComboBoxView *filterView = [[SISSComboBoxView alloc] initWithFrame:CGRectMake(0, NAVIGATION_HEIGHT, SCREEN_WIDTH, 44) isHouseResource:YES isCooperation:NO];
    filterView.delegate = self;
    
    [self.view addSubview:filterView];
    self.filterView = filterView;
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    // 自动行高
    tableView.estimatedRowHeight = 80;
    tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    [tableView registerNib:[UINib nibWithNibName:@"SISSHousingCell" bundle:nil] forCellReuseIdentifier:housingCellID];
    
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    // 排序按钮
    UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sortButton setTitle:@"排序" forState:UIControlStateNormal];
    sortButton.layer.cornerRadius = 12;
    sortButton.layer.masksToBounds = YES;
    [sortButton setBackgroundImage:[ImageWithColor imageWithColor:[UIColor darkGrayColor]]  forState:UIControlStateNormal];
    sortButton.titleLabel.font = [UIFont systemFontOfSize:15];
    sortButton.alpha = 0.8;
    [sortButton addTarget:self action:@selector(sortedButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sortButton];
    
    UILabel *hintLabel = [[UILabel alloc] init];
    hintLabel.textAlignment = NSTextAlignmentCenter;
    hintLabel.textColor = [UIColor whiteColor];
    hintLabel.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.8];
    hintLabel.layer.cornerRadius = 12;
    hintLabel.hidden = YES;
    hintLabel.layer.masksToBounds = YES;
    [self.view addSubview:hintLabel];
    self.hintLabel = hintLabel;
    
    // 自动布局
    CGSize sortBtnSize = CGSizeMake(66, 30);
    CGFloat margin = 10;
    CGFloat bottomViewHeight = 0;
    WeakSelf
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.filterView.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.bottom.mas_equalTo(-bottomViewHeight);
    }];
    
    [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view);
        make.size.mas_equalTo(CGSizeMake(250, 30));
        make.bottom.equalTo(weakSelf.view).offset(- 12 * margin);
    }];
    
    [sortButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view).offset(-4 * margin);
        make.bottom.equalTo(weakSelf.view).offset(-8 * margin);
        make.size.mas_equalTo(sortBtnSize);
    }];
    
}

#pragma mark - Getter & Setter

- (NSMutableArray<SISSHouseResourceModel *> *)houseResourceArr {
    if (!_houseResourceArr) {
        _houseResourceArr = [NSMutableArray array];
    }
    return _houseResourceArr;
}


- (NSString *)keyword {
    
    if (_keyword == nil) {
        _keyword = @"";
    }
    return _keyword;
}

- (NSArray *)area {
    if (_area == nil) {
        _area = [NSArray array];
    }
    return _area;
}

- (NSArray *)direction {
    if (_direction == nil) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    if (_decoration == nil) {
        _decoration = [NSArray array];
    }
    return _decoration;
}

@end
